<?php
require('socket.php');
$ws = new socket('192.168.0.114', '8080', 10);
//设置回调函数
$ws->function['add'] = 'user_add_callback';
$ws->function['send'] = 'send_callback';
$ws->function['close'] = 'close_callback';
$ws->start_server();
//回调函数

//添加用户数量
function user_add_callback($ws) {
    $data = count($ws->accept);
    send_to_all($data, 'num', $ws);
}

//返回用户数量
function close_callback($ws) {
    $data = count($ws->accept);
    send_to_all($data, 'num', $ws);
}

//返回信息，对信息进行处理
function send_callback($data, $userId, $ws) {
    $data = json_encode(array(
        'text' => $data,
        'user' => $userId,
    ));
    send_to_all($data, 'text', $ws);
}

//向所有连接至socket的用户发送消息
function send_to_all($data, $type, $ws){
    //获取消息跟类型
    $res = array(
        'msg' => $data,
        'type' => $type,
    );
    //变为JSON数据
    $res = json_encode($res);
    //调用frame方法
    $res = $ws->frame($res);
    //发送数据
    foreach ($ws->accept as $key => $value) {
        socket_write($value, $res, strlen($res));
    }
}